package com.doujiang.Controller;

import com.doujiang.domain.Comment;
import com.doujiang.domain.Rating;
import com.doujiang.domain.User;
import com.doujiang.service.ICommentService;
import com.doujiang.service.IRatingService;
import com.doujiang.service.IUserService;
import com.doujiang.service.zzqICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/commentss")
@CrossOrigin
public class zzqCommentController {

    @Autowired
    private zzqICommentService commentService;
    @Autowired
    private IRatingService ratingService;
    @Autowired
    private IUserService userService;

    /**
     * 获取所有评论
     */
    @GetMapping
    public List<Comment> getAllComments() {
        return commentService.list();
    }

    /**
     * 根据评论ID获取评论
     */
    @GetMapping("/{id}")
    public ResponseEntity<Comment> getCommentById(@PathVariable("id") Long id) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(comment);
    }

    /**
     * 根据电影ID获取评论列表
     */
    @GetMapping("/movie/{movieId}")
    public ResponseEntity<List<Map<String, Object>>> getCommentsByMovieIdWithRating(
            @PathVariable("movieId") Long movieId,
            @RequestParam(value = "currentUserId", required = false) Long currentUserId) {
        try {
            List<Comment> comments = commentService.getCommentsByMovieId(movieId);
            List<Rating> ratings = ratingService.getRatingsByMovieId(movieId);

            // 如果没有传入当前用户ID，使用默认值2（兼容性处理）
            final Long finalCurrentUserId = currentUserId != null ? currentUserId : 2L;

            List<Map<String, Object>> result = comments.stream().map(comment -> {
                Map<String, Object> map = new HashMap<>();
                
                // 解析点赞JSON
                comment.parseLikesJson();
                
                // 获取用户信息
                User user = userService.getById(comment.getUserId());
                if (user != null) {
                    // 将用户信息添加到评论中
                    comment.setUsername(user.getUsername());
                    comment.setUserAvatar(user.getAvatar());
                } else {
                    // 如果找不到用户，设置默认值
                    comment.setUsername("用户" + comment.getUserId());
                    comment.setUserAvatar(null);
                }
                
                map.put("comment", comment);

                // 评分信息
                Optional<Rating> ratingOpt = ratings.stream()
                        .filter(r -> r.getUserId().equals(comment.getUserId()))
                        .findFirst();
                map.put("rating", ratingOpt.orElse(null));

                // 👇 是否点赞
                boolean likedByUser = comment.getLikes() != null && comment.getLikes().contains(finalCurrentUserId);
                map.put("likedByUser", likedByUser);  // 👈 确保这个字段返回给前端

                return map;
            }).collect(Collectors.toList());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }


    /**
     * 添加新评论
     */
    @PostMapping
    public ResponseEntity<Boolean> addComment(@RequestBody Comment comment) {
        boolean result = commentService.saveComment(comment);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据用户ID获取评论列表（包含点赞状态）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getUserCommentsWithLikeStatus(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "currentUserId", required = false) Long currentUserId) {
        try {
            List<Comment> comments = commentService.getCommentsByUserId(userId);
            
            // 如果没有传入当前用户ID，使用默认值2（兼容性处理）
            final Long finalCurrentUserId = currentUserId != null ? currentUserId : 2L;

            List<Map<String, Object>> result = comments.stream().map(comment -> {
                Map<String, Object> map = new HashMap<>();
                
                // 解析点赞JSON
                comment.parseLikesJson();
                
                // 获取用户信息
                User user = userService.getById(comment.getUserId());
                if (user != null) {
                    comment.setUsername(user.getUsername());
                    comment.setUserAvatar(user.getAvatar());
                } else {
                    comment.setUsername("用户" + comment.getUserId());
                    comment.setUserAvatar(null);
                }
                
                map.put("comment", comment);

                // 是否点赞
                boolean likedByUser = comment.getLikes() != null && comment.getLikes().contains(finalCurrentUserId);
                map.put("likedByUser", likedByUser);

                return map;
            }).collect(Collectors.toList());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/{id}/like")
    public ResponseEntity<Map<String, Object>> toggleLike(@PathVariable("id") Long id, @RequestBody Map<String, Object> payload) {
        try {
            // 获取 userId
            Object userIdObj = payload.get("userId");
            if (!(userIdObj instanceof Number)) {
                return ResponseEntity.badRequest().build();
            }
            Long userId = ((Number) userIdObj).longValue();

            // 获取评论
            Comment comment = commentService.getById(id);
            if (comment == null) {
                return ResponseEntity.notFound().build();
            }

            // 解析 JSON
            comment.parseLikesJson();  // 👈 检查这里是否抛异常

            // 判断是否已点赞
            boolean liked = comment.getLikes().contains(userId);

            if (liked) {
                comment.getLikes().remove(userId);
                comment.setUseful(comment.getUseful() - 1);
            } else {
                comment.getLikes().add(userId);
                comment.setUseful(comment.getUseful() + 1);
            }

            // 序列化 likes 到 likesJson
            comment.serializeLikesJson();  // 👈 检查这里是否抛异常

            // 更新评论
            commentService.updateById(comment);

            // 重新解析点赞状态，确保返回正确的状态
            comment.parseLikesJson();
            boolean finalLikedByUser = comment.getLikes().contains(userId);
            
            // 创建一个包含点赞状态的响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("id", comment.getId());
            response.put("useful", comment.getUseful());
            response.put("likedByUser", finalLikedByUser);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();  // 👈 一定要看控制台日志
            return ResponseEntity.status(500).build();
        }
    }




    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> deleteComment(@PathVariable("id") Long id) {
        boolean result = commentService.removeById(id);
        return ResponseEntity.ok(result);
    }
}
